package cn.lunkr.sdkdemo.ui.table.fragment;


import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.apache.commons.lang.StringUtils;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.slidingpanelayout.widget.SlidingPaneLayout;
import cn.lunkr.base.config.Actions;
import cn.lunkr.base.entity.mail.SimpleMail;
import cn.lunkr.base.ui.BasicFragment;
import cn.lunkr.mailui.ui.MailComposeActivity2;
import cn.lunkr.mailui.ui.MailsBarFragment;
import cn.lunkr.mailui.ui.MailsFragment;
import cn.lunkr.mailui.ui.listener.MailBarFragmentListener;
import cn.lunkr.mailui.ui.listener.ReadMailBarListener;
import cn.lunkr.mailui.ui.mail.ReadMailBarFragment;
import cn.lunkr.sdkdemo.R;
import cn.lunkr.sdkdemo.databinding.FragmentTableEmailBinding;
import cn.lunkr.sdkdemo.ui.table.activity.TableSearchActivity;

public class TableEmailFragment extends BasicFragment implements MailBarFragmentListener, ReadMailBarListener {

    private FragmentTableEmailBinding mViewBinding;
    private SimpleMail mMail;

    public TableEmailFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mViewBinding = FragmentTableEmailBinding.inflate(getLayoutInflater());
        initCallBack();
        return mViewBinding.getRoot();
    }

    private void initCallBack() {
        requireActivity().getOnBackPressedDispatcher().addCallback(
                getViewLifecycleOwner(),
                new EmailOnBackPressedCallback(mViewBinding.slidingPaneLayout));
    }

    @Override
    public void onEditPattern(boolean state) {
        // 平板不需要处理
    }

    // 记录从列表选择的邮件
    @Override
    public boolean onItemClick(int position, SimpleMail message, Bundle extraData) {
        Fragment fragment = getChildFragmentManager().findFragmentByTag("detail_frag");
        FragmentTransaction ft = getChildFragmentManager().beginTransaction();
        if (fragment == null) {
            ft.replace(R.id.detail_container, ReadMailBarFragment.class, extraData, "detail_frag"); // 首次是通过创建传递
        }
        if (mViewBinding.slidingPaneLayout.isOpen()) {
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        }
        ft.commit();
        mViewBinding.slidingPaneLayout.open();
        if (mMail == null) {
            mMail = message;
        } else if (!StringUtils.equals(message.id, mMail.id)) {
            mMail = message;
            readAnotherMail(extraData); // 后续是通过广播传递
        }
        return true;
    }

    @Override
    public void onWriteClick() {
//        Bundle bundle = new Bundle();
//        bundle.putInt(MailComposeFragment.COMPOSE_MODE, MailComposeFragment.COMPOSE_MODE_WRITE);
//        MailComposeActivity.start(getActivity(), bundle);
        startActivity(new Intent(getActivity(), MailComposeActivity2.class));
    }

    @Override
    public boolean onMailSearchClick() {
//        startActivity(new Intent(getActivity(), GlobalSearchActivity.class));
        Intent searchIntent = new Intent();
        searchIntent.setClass(getActivity(), TableSearchActivity.class);
        searchIntent.putExtra("searchViewOnToolbar", true);
        startActivity(searchIntent);
        return true;
    }

    //
    private void changeMailList(Intent intent) {
        sendUpdateMailStatus(intent);
    }

    /**
     * 响应 单侧情况返回到列表frag
     */
    private static class EmailOnBackPressedCallback extends OnBackPressedCallback
            implements SlidingPaneLayout.PanelSlideListener {

        private final SlidingPaneLayout mSlidingPaneLayout;


        EmailOnBackPressedCallback(@NonNull SlidingPaneLayout slidingPaneLayout) {
            super(slidingPaneLayout.isSlideable() && slidingPaneLayout.isOpen());
            mSlidingPaneLayout = slidingPaneLayout;
            slidingPaneLayout.addPanelSlideListener(this);
        }

        @Override
        public void handleOnBackPressed() {
            mSlidingPaneLayout.closePane();
        }

        @Override
        public void onPanelSlide(@NonNull View panel, float slideOffset) {
        }

        @Override
        public void onPanelOpened(@NonNull View panel) {
            setEnabled(true);
        }

        @Override
        public void onPanelClosed(@NonNull View panel) {
            setEnabled(false);
        }
    }

    public boolean onBackPressed() {
        MailsBarFragment fragment = findMailListFragment();
        return fragment != null && fragment.onBackPressed();
    }

    private MailsBarFragment findMailListFragment() {
        Fragment fragment = getChildFragmentManager().findFragmentById(R.id.list_container);
        if (fragment != null && fragment instanceof MailsBarFragment) {
            return (MailsBarFragment) fragment;
        }
        return null;
    }


    @Override
    public void slideMailView(boolean needExpand) {
        if (mViewBinding.slidingPaneLayout.isSlideable()) {
            return;
        }
        View detailView = mViewBinding.slidingPaneLayout.getChildAt(1);
        if (detailView == null) return;
        if (needExpand) {
            ObjectAnimator a1 = ObjectAnimator.ofFloat(mViewBinding.listContainer, "X", 1f, 0f);
            ObjectAnimator a2 = ObjectAnimator.ofFloat(mViewBinding.listContainer, "Y", 1f, 0f);
            AnimatorSet set = new AnimatorSet();
            set.play(a1).with(a2);
            set.setDuration(500).start();
            mViewBinding.listContainer.setVisibility(View.GONE);
        } else {
            mViewBinding.listContainer.setVisibility(View.VISIBLE);
        }
    }

    /**
     * @param mail 由于平台上下封阅读为单次响应，考虑单独定位处理
     */
    @Override
    public void preOrNext(SimpleMail mail) {
        Bundle bundle = new Bundle();
        bundle.putParcelable(MailsFragment.ITEM_BUNDLE_MAIL, mail);
        readAnotherMail(bundle); // 通知读信加载
        mMail = mail;

        // 定位列表同步已读状态
        Fragment mailFrag = getChildFragmentManager().findFragmentById(R.id.list_container);
        if (mailFrag instanceof MailsBarFragment) {
            ((MailsBarFragment) mailFrag).handleNotifyRead(mail);
        }
    }

    /**
     * @param mailId 操作响应由一方处理
     */
    @Override
    public void delete(String mailId) {
        Fragment mailFrag = getChildFragmentManager().findFragmentById(R.id.list_container);
        if (mailFrag instanceof MailsFragment) {
            ((MailsFragment) mailFrag).deleteMail(mailId);
        }

        getChildFragmentManager().beginTransaction().replace(R.id.detail_container, null).commit();
    }

    @Override
    public void close() {
        Fragment readMailFrag = getChildFragmentManager().findFragmentById(R.id.detail_container);
        if (readMailFrag == null) return;
        getChildFragmentManager().beginTransaction().remove(readMailFrag).commit();
    }

    /**
     * 变更当前阅读邮件
     */
    private void readAnotherMail(Bundle bundle) {
        Intent intent = new Intent(Actions.ACTION_READ_MAIL(requireContext()));
        intent.putExtras(bundle);
        LocalBroadcastManager.getInstance(requireContext()).sendBroadcast(intent);
    }

    private void sendUpdateMailStatus(Intent intent) {
        intent.setAction(Actions.ACTION_MAIL_STATUS_UPDATE);
        LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
    }
}